package com.hmdp.schedule;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.entity.Shop;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

/**
 * @author 张旭
 * @version 1.0
 */
@Component
@Slf4j
public class PreCacheJob {
    @Resource
    private IShopService shopService;

    @Autowired
    private CacheClient cacheClient;

    @Autowired
    private RedissonClient redissonClient;

    private List<Long> shopIDList = shopService.getShopIDLists();


    /**
     * 店铺详情信息的缓存预热
     */
    @Scheduled(cron = "0 0 4 * * *")
    public void doShopCache() {

        for (Long shopID : shopIDList) {
            RLock lock = redissonClient.getLock("lock:order:" + shopID);
            try {
                //第二个参数为-1，表示锁每隔10秒会自动续约
                boolean isLock = lock.tryLock(0, -1, TimeUnit.MILLISECONDS);
                if (isLock) {
                    String key = CACHE_SHOP_KEY + shopID;
                    Shop shop = shopService.getById(shopID);
                    cacheClient.set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
                }
            } catch (Exception e) {
                log.error("redis set key error", e);
            } finally {
                lock.unlock();
            }
        }
    }

}
